package com.csxy.yuekaiyeye.service.Impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.csxy.yuekaiyeye.service.OssService;
import com.csxy.yuekaiyeye.util.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceimpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        InputStream inputStream = null;
        String url = null;
            try {
                //创建OSS实例
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                //获取文件
                inputStream = file.getInputStream();
                //获取文件名称
                String fileName = file.getOriginalFilename();
                //在文件名称中添加uuid，防止重复
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                fileName = uuid + fileName;
                //把文件按时间分类
                String detePath = new java.text.SimpleDateFormat("yyyy/MM/dd").format(new java.util.Date());
                fileName = detePath + "/" + fileName;
                //上传文件
                ossClient.putObject(bucketName, fileName, inputStream);
                //关闭OSSClient
                ossClient.shutdown();
                //上传之后文件路径
                url = "https://" + bucketName + "." + endpoint + "/" + fileName;

                } catch (Exception e) {
                e.printStackTrace();
                }
                // TODO: 2020/5/7 上传头像
                return url;

        }
}